/*
 * Copyright 2010 Alexey Romensky
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

/*
 * User: Alexey Romensky
 * Date: 21.02.2010
 * Time: 22:42:55
 */
package com.googlecode.gwt.logging.base.client.util;

import com.google.gwt.core.client.GWT;

public final class LogUtil {

    /**
     * Retrieve caller's execution context. Would work properly only in Development mode
     * and Web mode with <code>-draftCompile</code> option and stacktrace emulation turned on.
     *
     * @param callerFileName number of nested calls to skip
     * @return caller's execution context
     */
    @SuppressWarnings({"ThrowableInstanceNeverThrown"})
    public static StackTraceElement getContext(String callerFileName) {

        final Throwable throwable = new Throwable();
        final StackTraceElement[] stackTrace = throwable.getStackTrace();

        if (!GWT.isScript() || stackTrace[0].getLineNumber() != 0) {

            for (int i = 1; i < stackTrace.length; i++) {

                if (callerFileName.equals(stackTrace[i].getFileName())) {
                    return stackTrace[i + 1];
                }
            }
        }

        return null;
    }

    public static void stackTraceToString(StringBuilder text, Throwable throwable) {

        while (throwable != null) {

            text.append(throwable.getClass().getName());
            text.append(": ");
            text.append(throwable.getMessage());
            text.append('\n');

            final StackTraceElement[] stackTraceElements = throwable.getStackTrace();
            for (StackTraceElement element : stackTraceElements) {

                text.append("    at ");
                text.append(element);
                text.append('\n');
            }

            throwable = throwable.getCause();

            if (throwable != null) {
                text.append("Caused by: ");
            }
        }
    }

    private LogUtil() {
        // empty
    }
}
